package app.foodnote;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import app.foodnote.db.FoodNotesDataSource;
import app.foodnote.db.MySQLiteHelper;

public class FoodSearch extends ListActivity{

	 private FoodNotesDataSource datasource;
	 public final static String ID_EXTRA = "app.foodnote._ID";
	 public final static String FOOD_SEARCH = "app.foodnote.food_search";
	 
	 Cursor cursor;
	 private SharedPreferences pref=null;
	 AlertDialog.Builder viewDetail;
	 ListView listView;
	 EditText EditSearch;
	 Button btnSearchFood;
	 Button btnSearchCity;
	
	 private final int CONTEXT_MENU_ID = 1;
     private IconContextMenu iconContextMenu = null;
     
     private final int MENU_ITEM_1_ACTION = 1;
     private final int MENU_ITEM_2_ACTION = 2;
     private final int MENU_ITEM_3_ACTION = 3;
     private final int MENU_ITEM_4_ACTION = 4;
     
     String Id = null;
     
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Danh Sách Món Ăn");
        setContentView(R.layout.form_search);
        Resources res = getResources();
        
        pref=null;
        datasource = new FoodNotesDataSource(this);
        EditSearch = (EditText)findViewById(R.id.EditSearch);
        btnSearchFood = (Button)findViewById(R.id.SearchFood);
        btnSearchCity = (Button)findViewById(R.id.SearchCity);
        OnClickListener SF=new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SearchFood();
			}
		};
		OnClickListener SA = new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				SearchAddr();
			}
		};
		
		btnSearchCity.setOnClickListener(SA);
		btnSearchFood.setOnClickListener(SF);
		
		iconContextMenu = new IconContextMenu(this, CONTEXT_MENU_ID);
        iconContextMenu.addItem(res, "Cập Nhật", R.drawable.update, MENU_ITEM_1_ACTION);
        iconContextMenu.addItem(res, "Xóa", R.drawable.delete, MENU_ITEM_2_ACTION);
        iconContextMenu.addItem(res, "Chi Tiết", R.drawable.detail, MENU_ITEM_3_ACTION);
        iconContextMenu.addItem(res, "Hiển Thị Trên Bản Đồ", R.drawable.showmap, MENU_ITEM_4_ACTION);
        
        iconContextMenu.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
            public void onClick(int menuId) {
                    switch(menuId) {
                    case MENU_ITEM_1_ACTION:
                        	Intent intentFoodPlace = new Intent(FoodSearch.this, FoodAdd.class);
            				intentFoodPlace.putExtra(ID_EXTRA, Id);
            				startActivity(intentFoodPlace);
                            break;
                    case MENU_ITEM_2_ACTION:
                            datasource = new FoodNotesDataSource(getApplicationContext());
                            datasource.openToWrite();
                            datasource.deleteFoodNote(Id);
                            datasource.close();
                            initList();
                            Toast.makeText(getApplicationContext(), "Bạn đã xóa thành công món ăn với id " + Id, Toast.LENGTH_LONG).show();
                            break;
                    case MENU_ITEM_3_ACTION:
                        	Intent detail = new Intent(FoodSearch.this, DetailActivity.class);
                        	detail.putExtra(ID_EXTRA, Id);
                        	detail.putExtra(FOOD_SEARCH, true);
                            startActivity(detail);
                            break;
                    case MENU_ITEM_4_ACTION:
                    	datasource.openToRead();
                		Cursor c = datasource.getFoodNoteById(Id);
                		c.moveToFirst();
                		double LAT_EXTRA = datasource.getLatitude(c);
                		double LOG_EXTRA = datasource.getLongitude(c);
                		c.close();
                		datasource.close();
                		Intent intentMaps = new Intent(FoodSearch.this, LocationActivity.class);
                		intentMaps.putExtra("LAT_EXTRA", LAT_EXTRA);
                		intentMaps.putExtra("LOG_EXTRA", LOG_EXTRA);
                		startActivity(intentMaps);
                            break;
                    }
            }
        });
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		
		this.Id = String.valueOf(id);
		showDialog(CONTEXT_MENU_ID);
		/*String Id = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_ID));
		String name = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.FOOD_NAME));
		String address = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.ADDRESS));
		String city = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.CITIES));
		String phonenumber = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.PHONE_NUMBER));
		String othernote = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.OTHER_NOTES));
		viewDetail = new AlertDialog.Builder(this);
		viewDetail.setTitle("Chi Tiết Món Ăn");
		viewDetail.setMessage("Id : " + Id + "\nTên Món Ăn : " + name + "\nĐịa chỉ : " + address + " " + city
				+ "\nĐiện Thoại : " + phonenumber + "\nGhi Chú : " + othernote);
		viewDetail.setPositiveButton("Đồng Ý",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				});
		viewDetail.setNegativeButton("Cập Nhật", new DialogInterface.OnClickListener() {
			
			public void onClick(DialogInterface dialog, int which) {
				Intent intentFoodPlace = new Intent(FoodSearch.this, FoodAdd.class);
				intentFoodPlace.putExtra(ID_EXTRA, cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_ID)));
				
				startActivity(intentFoodPlace);			
			}
		});
		viewDetail.show();*/
		
	}
	@Override
	protected void onResume() {
		
	    /*List<FoodNote> values = datasource.getAllFoodNotes();
        ArrayAdapter<FoodNote> adapter = new ArrayAdapter<FoodNote>(this,
        		android.R.layout.simple_list_item_multiple_choice, values);
		Log.d("Gia tri", "Gia tri o vi tri " + values.get(0));*/
		pref = PreferenceManager.getDefaultSharedPreferences(this);
        initList();
        pref.registerOnSharedPreferenceChangeListener(prefListener);
	    
	    super.onResume();

	  }
	
	  public void SearchAddr(){
		    datasource.openToRead();
		    cursor = datasource.getSearchAddr(EditSearch.getText().toString());
		    startManagingCursor(cursor);
		    String[] from = new String[] {MySQLiteHelper.FOOD_NAME, MySQLiteHelper.ADDRESS};
		    int[] to = new int[] {R.id.foodname, R.id.address};
		    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
	        setListAdapter(adapter);
	        datasource.close();
	  }
	  
	  public void SearchFood(){
		    datasource.openToRead();
		    cursor = datasource.getSearchFood(EditSearch.getText().toString());
		    startManagingCursor(cursor);
		    String[] from = new String[] {MySQLiteHelper.FOOD_NAME, MySQLiteHelper.ADDRESS};
		    int[] to = new int[] {R.id.foodname, R.id.address};
		    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
	        setListAdapter(adapter);
	        datasource.close();
	  }

	  @Override
	  protected void onPause() {
		  //datasource.close();
	      super.onPause();
	  }
	  @Override
	  protected void onDestroy(){
		  super.onDestroy();
		  datasource.close();
	  }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.form_search_option, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item){
		if(item.getItemId()==R.id.setting){
			startActivity(new Intent(FoodSearch.this, formsort.class));
			return true;
		}
		return super.onOptionsItemSelected(item);
		
	}
	 @Override
	    protected Dialog onCreateDialog(int id) {
	        if (id == CONTEXT_MENU_ID) {
	                return iconContextMenu.createMenu("Menu");
	        }
	        return super.onCreateDialog(id);
	    }
	
	//Khoi tao list
	private void initList(){
        datasource.openToRead();
        if (cursor!= null) {
            stopManagingCursor(cursor);
           cursor.close();
          }
        //cursor = datasource.getAllEntry();
        cursor = datasource.getAllEntrySort(pref.getString("sort", "foodname"));
	    startManagingCursor(cursor);
	    String[] from = new String[] {MySQLiteHelper.FOOD_NAME, MySQLiteHelper.ADDRESS};
	    int[] to = new int[] {R.id.foodname, R.id.address};
	    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
        setListAdapter(adapter);
	}
	
   private SharedPreferences.OnSharedPreferenceChangeListener prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
		
		public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
				String key) {
			// TODO Auto-generated method stub
			if(key.equals("sort")){
				initList();
			}
		}
	};
}
